<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { CloseBold, Select, Search } from '@element-plus/icons-vue'
import IntroDrawer from './components/IntroDrawer.vue'
import ApplyApi from '../../service/api/apply/apply'
// 定义接口
interface ProjectDetail {
  title: string
  status: number
  start_time: string
  over_time: string
  people_num: number
}

interface UserDetail {
  name: string
  sex: string | null
  stu_num: number
  avatar: string | null
  faculty: string | null
  introduction: string
}

interface ApplyListItem {
  form_id: number
  status: number
  reason: string | null
  projectDetail: ProjectDetail
  userDetail: UserDetail
}

interface ApiResponse {
  code: number
  data: {
    list: ApplyListItem[]
  }
}
//表格加载状态
const loading = ref(false)

//跳转链接函数
const jumpLink = (url: string) => {
  window.open(url, '_blank')
}

//打开修改弹窗并同步值
const handleUpdate = (row: any) => {
  approveRef.value.open(row)
}

const handleAdd = () => {
  rejectRef.value.open()
}

const handleImport = () => {
  excelDialog.value.open()
}

//编辑
const approveRef = ref()

//添加
const rejectRef = ref()

//导入
const excelDialog = ref()

const introDialog = ref()

// 获取待审批表格数据函数
const applyList = ref<any>([])
const historyList = ref<any>([])
const getApplyList = async (): Promise<void> => {
  // loading.value = true
  await ApplyApi.getApplyList().then((res: any) => {
    if (res.code != 200) {
      ElMessage.error('获取数据失败')
    } else {
      // 待审批数据
      const applyListBrief = ref<any>([])
      res.data.list.forEach((item: any) => {
        if (item.status == 0) {
          applyListBrief.value.push(item)
          applyList.value = [...applyListBrief.value]
        }
      })
      // 审批历史
      const historyListBrief = ref<any>([])
      res.data.list.forEach((item: any) => {
        if (item.status != 0) {
          historyListBrief.value.push(item)
          historyList.value = [...historyListBrief.value]
        }
      })
      applyListBrief.value = []
      historyListBrief.value = []
      // 筛选待审批项目名
      const titleEnumArray = Array.from(
        new Set(
          res.data.list
            .filter((item: any) => item.status == 0)
            .map((item: any) => {
              return item.projectDetail.title
            })
        )
      )
      filtersProjectTitleKey.value = titleEnumArray.map((item: any) => {
        return {
          text: item,
          value: item
        }
      })
      // 筛选待审批历史项目名
      const titleEnumArrayHistory = Array.from(
        new Set(
          res.data.list
            .filter((item: any) => item.status != 0)
            .map((item: any) => {
              return item.projectDetail.title
            })
        )
      )
      filtersProjectTitleHistoryKey.value = titleEnumArrayHistory.map((item: any) => {
        return {
          text: item,
          value: item
        }
      })
    }
  })
}

//获取表格数据
getApplyList()

// faculty映射
const facultyMap = ref(['全体', '计院', '理学院', '管院'])
const approve = async (row: any, attitude: string) => {
  approveRef.value.open(row, attitude)
}
const reject = async (row: any, attitude: string) => {
  approveRef.value.open(row, attitude)
}
const intro = (row: any) => {
  // console.log(row)
  introDialog.value.open(row)
}
// 审批后更新数据
const OnUpdate = () => {
  // console.log('OnUpdate')
  // window.location.reload()
  getApplyList()
}
// 切换到审批记录或待审批
const isHistory = ref(false)
const handleSwitch = () => {
  isHistory.value = !isHistory.value
}
const filtersProjectTitleKey = ref({})
const filtersProjectTitleHistoryKey = ref({})
// 项目名筛选
const filterTitle = (value: any, row: any) => {
  return row.projectDetail.title === value
}
// 学院筛选
const filterFaculty = (value: any, row: any) => {
  return row.projectDetail.faculty === value
}
</script>

<template>
  <PageContainer>
    <el-header class="header">
      <el-button type="primary" plain @click="handleSwitch">{{
        isHistory ? '切换到审批界面' : '切换到审批历史'
      }}</el-button>
    </el-header>
    <el-main class="main">
      <el-table
        :data="historyList"
        :default-sort="[{ prop: 'id', order: 'descending' }]"
        v-loading="loading"
        max-height="80vh"
        flexible="true"
        v-if="isHistory"
      >
        <el-table-column type="index" label="序号" sortable width="80" />
        <el-table-column prop="userDetail.sex" label="性别" width="100">
          <template #default="scope">
            <div class="name-wrapper">
              <img v-if="scope.row.sex == 0" src="../../assets/girl.png" alt="" />
              <img v-else-if="scope.row.sex == 1" src="../../assets/boy.png" alt="" />
              <span v-else>未知</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userDetail.avatar" label="头像" width="120">
          <template #default="scope">
            <div class="name-wrapper">
              <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="" />
              <img v-else src="../../assets/blankAvatar.png" alt="" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userDetail.name" label="姓名" width="150">
          <template #default="scope">
            <div class="name-wrapper">
              <span>{{ scope.row.userDetail.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userDetail.stu_num" label="学号" width="160"></el-table-column>

        <el-table-column
          prop="projectDetail.title"
          label="所报项目"
          width="200"
          :filters="filtersProjectTitleHistoryKey"
          :filter-method="filterTitle"
          filter-placement="bottom-end"
        >
        </el-table-column>
        <el-table-column
          prop="userDetail.faculty"
          label="学院"
          width="200"
          :filters="[
            { text: '计算机学院', value: 1 },
            { text: '理学院', value: 2 },
            { text: '管院', value: 3 },
            { text: '医学院', value: 4 }
          ]"
          :filter-method="filterFaculty"
          filter-placement="bottom-end"
        >
          <template #default="scope">{{
            scope.row.userDetail.faculty === null
              ? '未知'
              : facultyMap[scope.row.userDetail.faculty]
          }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="160">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="info">待审批</el-tag>
            <el-tag v-else-if="scope.row.status == 1" type="success">已通过</el-tag>
            <el-tag v-else type="danger">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240">
          <template #default="scope">
            <el-button type="primary" plain round @click="intro(scope.row.userDetail)"
              >查看简历</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-table
        :data="applyList"
        :default-sort="[{ prop: 'id', order: 'descending' }]"
        v-loading="loading"
        max-height="80vh"
        flexible="true"
        v-else
      >
        <el-table-column type="index" label="序号" sortable width="80" />
        <el-table-column prop="userDetail.sex" label="性别" width="100">
          <template #default="scope">
            <div class="name-wrapper">
              <img v-if="scope.row.sex == 0" src="../../assets/girl.png" alt="" />
              <img v-else-if="scope.row.sex == 1" src="../../assets/boy.png" alt="" />
              <span v-else>未知</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userDetail.avatar" label="头像" width="120">
          <template #default="scope">
            <div class="name-wrapper">
              <img v-if="scope.row.avatar" :src="scope.row.avatar" alt="" />
              <img v-else src="../../assets/blankAvatar.png" alt="" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userDetail.name" label="姓名" width="150">
          <template #default="scope">
            <div class="name-wrapper">
              <span>{{ scope.row.userDetail.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userDetail.stu_num" label="学号" width="160"></el-table-column>

        <el-table-column
          prop="projectDetail.title"
          label="所报项目"
          width="200"
          :filters="filtersProjectTitleKey"
          :filter-method="filterTitle"
          filter-placement="bottom-end"
        >
        </el-table-column>
        <el-table-column
          prop="userDetail.faculty"
          label="学院"
          width="200"
          :filters="[
            { text: '计算机学院', value: 1 },
            { text: '理学院', value: 2 },
            { text: '管院', value: 3 },
            { text: '医学院', value: 4 }
          ]"
          :filter-method="filterFaculty"
          filter-placement="bottom-end"
        >
          <template #default="scope">{{
            scope.row.userDetail.faculty === null
              ? '未知'
              : facultyMap[scope.row.userDetail.faculty]
          }}</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="160">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="info">待审批</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="审批操作" width="250">
          <template #default="scope">
            <div :style="{ display: 'flex', justifyContent: 'space-around' }">
              <el-button
                type="success"
                plain
                circle
                :icon="Select"
                @click="approve(scope.row, 'approve')"
              ></el-button>
              <el-button
                type="danger"
                plain
                circle
                :icon="CloseBold"
                @click="reject(scope.row, 'reject')"
              ></el-button>
              <el-button type="primary" plain round @click="intro(scope.row.userDetail)"
                >查看简历</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <ResourceEdit ref="approveRef" @update="OnUpdate"></ResourceEdit>
      <!-- <ResourceEdit ref="rejectRef" @update="OnUpdate"></ResourceEdit> -->
      <IntroDrawer ref="introDialog"></IntroDrawer>
      <ImportExcel
        ref="excelDialog"
        apiAddress="https://smarttool.wust.edu.cn:3001/api/admin/resource/upload"
      ></ImportExcel>
    </el-main>
  </PageContainer>
</template>

<style lang="scss" scoped>
.name-wrapper {
  display: flex;
  align-items: center;
  img {
    width: 70px;
    height: 70px;
    margin-right: 10px;
    border-radius: 50%;
  }
}
.header {
  display: flex;

  align-items: center;
  background-color: #fff;
  border-radius: 8px;
}

.main {
  background-color: #fff;
  margin-top: 20px;
  border-radius: 6px;
}
</style>
